//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Web.UI;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.BusinessLogic.Services;
using NopSolutions.NopCommerce.Common;
using NopSolutions.NopCommerce.Common.Utils;

namespace NopSolutions.NopCommerce.Web
{
    public partial class CategoryPage : BaseNopFrontendPage
    {
        private ICategoryService _categoryService;
        private ISettingService _settingService;
        private Category _category = null;

        public CategoryPage() {
            _categoryService = IoC.Resolve<ICategoryService>();
            _settingService = IoC.Resolve<ISettingService>();

            if (CategoryId > 0)
                _category = _categoryService.GetCategoryById(this.CategoryId);
        }

        protected override void OnInit(EventArgs e) {
            this.CreateChildControlsTree();

            Load += new EventHandler(CategoryPage_Load);
            base.OnInit(e);

            //if (Request.RequestContext.RouteData.Route != null) {
            //    Route r = Request.RequestContext.RouteData.Route as Route;
            //    if (r != null && r.Url.StartsWith("produse/")) {
            //        int catId = 0;
            //        if (!int.TryParse(Request.RequestContext.RouteData.Values["categoryId"].ToString(), out catId)) {
            //            if (int.TryParse(Request.RequestContext.RouteData.Values["categoryId"].ToString().Split('-')[0], out catId)) {
            //                var cat = this.CategoryService.GetCategoryById(catId);
            //                var catSeName = SEOHelper.GetSEName(cat.Name);
            //                Response.RedirectToRoutePermanent("CategoryRoute", new { categoryId = catId, categoryName = catSeName });
            //                Response.End();
            //            }
            //        }
            //    }
            //}            
        }

        void CategoryPage_Load(object sender, EventArgs e) {
            if (_category == null || _category.Deleted || !_category.Published)
                Response.Redirect(CommonHelper.GetStoreLocation());

            //title, meta
            string title = string.Empty;
            if (!string.IsNullOrEmpty(_category.LocalizedMetaTitle))
                title = _category.LocalizedMetaTitle;
            else {
                title = _category.LocalizedName;
            }
            SEOHelper.RenderTitle(this, title, true);
            SEOHelper.RenderMetaTag(this, "description", _category.LocalizedMetaDescription, true);
            SEOHelper.RenderMetaTag(this, "keywords", _category.LocalizedMetaKeywords, true);

            //canonical URL
            if (SEOHelper.EnableUrlRewriting && _settingService.GetSettingValueBoolean("SEO.CanonicalURLs.Category.Enabled")) {
                if (!CategoryName.Equals(SEOHelper.GetCategorySEName(_category))) {
                    string canonicalUrl = SEOHelper.GetCategoryUrl(_category);
                    if (Request.QueryString != null) {
                        for (int i = 0; i < Request.QueryString.Count; i++) {
                            string key = Request.QueryString.GetKey(i);
                            if (!String.IsNullOrEmpty(key) &&
                                (key.ToLowerInvariant() != "categoryid") &&
                                (key.ToLowerInvariant() != "sename")) {
                                canonicalUrl = CommonHelper.ModifyQueryString(canonicalUrl, key + "=" + Request.QueryString[i], null);
                            }
                        }
                    }

                    SEOHelper.RenderCanonicalTag(Page, canonicalUrl);
                }
            }

            if (!Page.IsPostBack) {
                NopContext.Current.LastContinueShoppingPage = CommonHelper.GetThisPageUrl(true);
            }
        }

        private void CreateChildControlsTree() {
            if (_category != null) {
                Control child = null;

                CategoryTemplate categoryTemplate = _category.CategoryTemplate;
                if (categoryTemplate == null)
                    throw new NopException(string.Format("Category template path can not be empty. CategoryID={0}", _category.CategoryId));

                child = base.LoadControl(categoryTemplate.TemplatePath);
                this.CategoryPlaceHolder.Controls.Add(child);
            }
        }

        public int CategoryId {
            get {
                return CommonHelper.RouteStringInt("categoryId");
            }
        }

        public string CategoryName {
            get {
                return CommonHelper.RouteString("categoryName");
            }
        }

        public override PageSslProtectionEnum SslProtected {
            get {
                return PageSslProtectionEnum.No;
            }
        }
    }
}